function modifyCSS_cargoImg() {
    var wid=$(".cargoImg").width();
    // console.log(wid);
    $(".cargoImg").height(wid+"px");
    // console.log($(".cargoImg").height());
}
function modifyCSS_cargoDesc(){
    var wid=$(".cargoImg").width();
    $(".cargoDesc").height(wid+"px");
}
function pageElemCenter() {
    var pageWid=$("#page").width();
    var pagePrevWid=$(".prevPage").width();
    var pagePrevBorderWid=parseInt($(".prevPage").css("border-width"));
    var pageElemWid=$(".pageElem").width();
    var pageElemBorderWid=parseInt($(".pageElem").css("border-width"));
    var pageElemLen=$(".pageElem").length;
    var pageElemMarginLeft=parseInt($(".pageElem").css("margin-left"));
    var val=(pageWid-(pagePrevWid+pagePrevBorderWid*2)*2)/2-(pageElemLen*(pageElemWid+pageElemBorderWid*2)+(pageElemLen-1)*pageElemMarginLeft)/2;

    $("#firstElem").css("margin-left",val+"px");
}
function showPanel(obj) {
    if(obj instanceof jQuery){
        if(obj.attr("id")=="cargo"){
            $("#cargo").css("background-image","linear-gradient(to bottom, white, white)");
            $("#orderForm").css("background-image","linear-gradient(to bottom, #2AA198, #4DC6AD)");
            $("#personalCenter").css("background-image","linear-gradient(to bottom, #2AA198, #4DC6AD)");
            $("#cargoPanel").show();
            $("#orderFormPanel").hide();
            $("#personalPanel").hide();
        }
        else if(obj.attr("id")=="orderForm"){
            $("#cargo").css("background-image","linear-gradient(to bottom, #2AA198, #4DC6AD)");
            $("#orderForm").css("background-image","linear-gradient(to bottom, white, white)");
            $("#personalCenter").css("background-image","linear-gradient(to bottom, #2AA198, #4DC6AD)");
            $("#cargoPanel").hide();
            $("#orderFormPanel").show();
            $("#personalPanel").hide();
        }
        else if(obj.attr("id")=="personalCenter"){
            $("#cargo").css("background-image","linear-gradient(to bottom, #2AA198, #4DC6AD)");
            $("#orderForm").css("background-image","linear-gradient(to bottom, #2AA198, #4DC6AD)");
            $("#personalCenter").css("background-image","linear-gradient(to bottom, white, white)");
            $("#cargoPanel").hide();
            $("#orderFormPanel").hide();
            $("#personalPanel").show();
        }
        // console.log(1)
        // $(".leftElem:hover").css("background-image","linear-gradient(to bottom, red, red)");
        return;
    }
    if($(obj).attr("id")=="cargo"){
        $("#cargo").css("background-image","linear-gradient(to bottom, white, white)");
        $("#orderForm").css("background-image","linear-gradient(to bottom, #2AA198, #4DC6AD)");
        $("#personalCenter").css("background-image","linear-gradient(to bottom, #2AA198, #4DC6AD)");
        $("#cargoPanel").show();
        $("#orderFormPanel").hide();
        $("#personalPanel").hide();
    }
    else if($(obj).attr("id")=="orderForm"){
        $("#cargo").css("background-image","linear-gradient(to bottom, #2AA198, #4DC6AD)");
        $("#orderForm").css("background-image","linear-gradient(to bottom, white, white)");
        $("#personalCenter").css("background-image","linear-gradient(to bottom, #2AA198, #4DC6AD)");
        $("#cargoPanel").hide();
        $("#orderFormPanel").show();
        $("#personalPanel").hide();
    }
    else if($(obj).attr("id")=="personalCenter"){
        $("#cargo").css("background-image","linear-gradient(to bottom, #2AA198, #4DC6AD)");
        $("#orderForm").css("background-image","linear-gradient(to bottom, #2AA198, #4DC6AD)");
        $("#personalCenter").css("background-image","linear-gradient(to bottom, white, white)");
        $("#cargoPanel").hide();
        $("#orderFormPanel").hide();
        $("#personalPanel").show();
    }
    // console.log(2);
    // $(".leftElem:hover").css("background-image","linear-gradient(to bottom, red, red)");
    return;
}

function recharge() {
    var str=$("#btn_rec").html();
    if(str=="充值"){
        $("#balance").removeAttr("disabled");
        $("#btn_rec").html("确定");
    }
    else {
        var account=$("#account").html();
        var balance=$("#balance").val();
        if(balance==""){
            alert("不允许空值被提交。");
        }
        else if(parseFloat(balance)<=0){
            alert("不允许0值和负值被提交。");
        }
        else{
            var data={
                "func":'recharge',
                'money':balance
            };
            // 通过ajax传值，修改余额
            $.ajax({
               url: "/store/customer/" + account,
                type: 'post',
                data: data,
                success: function () {
                    alert("充值成功。");
                    location.reload();
                },
                error: function (error) {
                    console.log(error)
                }
            });
            $("#balance").attr("disabled","disabled");
            $("#btn_rec").html("充值");
        }
    }
}

function modiBasic() {
    var str=$("#modi").html();
    if(str=="修改"){
        $(".basicInfo").removeAttr("disabled");
        $("#modi").html("保存");
    }
    else {
        var account=$("#account").html()
        // 通过ajax传值，修改基本信息
        var accountAlter=$("#basicInfo input[name='account']").val();
        var address=$("#basicInfo input[name='address']").val();
        var data={
            'func':"modiBasicInfo",
            'accountAlter':accountAlter,
            'address':address
        };
        if(accountAlter==""||address=="")
            alert("不允许空值被提交");
        else {
            $.ajax({
                url: "store/customer/" + account,
                type: 'post',
                data: data,
                success: function (data) {
                    if(data['num']==0)
                        alert("错误，该账户号已被占用。");
                    else if(data['num']==1)
                        alert("基本信息修改成功。");
                    else{
                        alert("基本信息修改成功，请重新登录。");
                        location.href="/store/login";
                    }
                },
                error: function (error) {
                    console.log(error)
                }
            });
            $(".basicInfo").attr("disabled", "disabled");
            $("#modi").html("修改");
        }
    }
}


function showPage() {
    // 获取账户号
    var account=$("#account").html()
    // console.log(account)
    // 获取未删除商品的个数，正确显示页面数
    var num=0
    $.ajax({
        url: "/store/customer/" + account,
        type: 'post',
        data: {
            'func': 'getNotDeleteCargoNum',
        },
        success:function (data) {
            num=data['num']
            // console.log(num)
            ElemNum=Math.trunc(num/12)+1
            // console.log(ElemNum)
            appendDiv=""
            for(var i=1;i<ElemNum;i++)
                appendDiv=appendDiv+"<div class='pageElem'>"+(i+1)+"</div>";
            $("#firstElem").after(appendDiv)
            pageElemCenter()
        },
        error: function (error) {
            console.log(error)
        }
    })
}

function clearCookie(){
    var keys=document.cookie.match(/[^ =;]+(?=\=)/g);
    if (keys) {
        for (var i = keys.length; i--;)
            document.cookie=keys[i]+'=0;expires=' + new Date( 0).toUTCString()
    }
}

// function orderFormLoad(){
//     $.ajax({
//         url: "http://127.0.0.1:5000/customer/" + account,
//         type:'post',
//         data:{
//             'func':'orderFormLoad',
//             'page':parseInt($(this).html())
//         },
//         success:function () {
//
//         },
//         error: function (error) {
//             console.log(error)
//         }
//     })
// }


$(function () {
    modifyCSS_cargoImg();
    modifyCSS_cargoDesc();
    showPanel($("#cargo"));
    showPage();

    // 清空cookie
    clearCookie();

    // 给点击分页绑定响应事件
    $(document).on("click", '.pageElem', function () {
        // 获取账户号
        var account=$("#account").html()
        // 设置当前页 1.取消.pageElem的class="currPage"，2.当前页添加属性class="currPage"
        $(".pageElem").removeClass("currPage");
        $(this).addClass("currPage");
        // console.log($(".currPage").html())

        $.ajax({
            url: "/store/customer/" + account,
            type:'post',
            data:{
                'func':'changePage',
                'page':parseInt($(this).html())
            },
            success:function (data) {
                var i=0;
                var dataLen=Object.keys(data).length;
                $(".cargoElem").each(function () {
                    if(i>=dataLen) {
                        $(this).hide();
                        i++;
                        return;
                    }
                    // console.log(i);
                    $(this).find(".cargoImg img").attr("src","../static/resources/cargos_photo/"+data[i]['photo']);
                    // $(this).find(".num").html(data[i]['price']+"元");
                    $(this).find(".carg_no").html(data[i]['no']);
                    $(this).find(".carg_name").html(data[i]['name']);
                    $(this).find(".carg_desc").html(data[i]['desc']);
                    $(this).find(".carg_price").html(data[i]['price']);
                    if($.cookie(data[i]['no'])!=null)
                        $(this).find(".num").html($.cookie(data[i]['no']));
                    else
                        $(this).find(".num").html(0);
                    $(this).show();
                    i++;
                });
            }
        });
    });

    // 给上一页下一页绑定单击响应事件
    // 上一页
    $(document).on("click", '.prevPage', function (){
        var start=1;
        var curr=$(".currPage:first").html();
        var prev=curr-1;   
        var account=$("#account").html()
	if(curr>start){
            // 设置当前页 1.取消.pageElem的class="currPage"，2.当前页添加属性class="currPage"
            $(".pageElem").removeClass("currPage");
            $(".pageElem").eq(prev-1).addClass("currPage");

            $.ajax({
            url: "/store/customer/" + account,
            type:'post',
            data:{
                'func':'changePage',
                'page':prev
            },
            success:function (data) {
                var i=0;
                var dataLen=Object.keys(data).length;
                $(".cargoElem").each(function () {
                    if(i>=dataLen) {
                        $(this).hide();
                        i++;
                        return;
                    }
                    // console.log(i);
                    $(this).find(".cargoImg img").attr("src","../static/resources/cargos_photo/"+data[i]['photo']);
                    // $(this).find(".num").html(data[i]['price']+"元");
                    $(this).find(".carg_no").html(data[i]['no']);
                    $(this).find(".carg_name").html(data[i]['name']);
                    $(this).find(".carg_desc").html(data[i]['desc']);
                    $(this).find(".carg_price").html(data[i]['price']);
                    if($.cookie(data[i]['no'])!=null)
                        $(this).find(".num").html($.cookie(data[i]['no']));
                    else
                        $(this).find(".num").html(0);
                    $(this).show();
                    i++;
                });
            }
        });
        }

    });

    // 下一页
    $(document).on("click", '.lastPage', function (){
        var end=parseInt($(".pageElem:last").html());
        var curr=parseInt($(".currPage:first").html());
        var next=curr+1;
        var account=$("#account").html()
        // console.log(end);
        // console.log(next);

        if(curr<end){
            // 设置当前页 1.取消.pageElem的class="currPage"，2.当前页添加属性class="currPage"
            $(".pageElem").removeClass("currPage");
            $(".pageElem").eq(next-1).addClass("currPage");

            $.ajax({
            url: "/store/customer/" + account,
            type:'post',
            data:{
                'func':'changePage',
                'page':next
            },
            success:function (data) {
                var i=0;
                var dataLen=Object.keys(data).length;
                $(".cargoElem").each(function () {
                    if(i>=dataLen) {
                        $(this).hide();
                        i++;
                        return;
                    }
                    // console.log(i);
                    $(this).find(".cargoImg img").attr("src","../static/resources/cargos_photo/"+data[i]['photo']);
                    // $(this).find(".num").html(data[i]['price']+"元");
                    $(this).find(".carg_no").html(data[i]['no']);
                    $(this).find(".carg_name").html(data[i]['name']);
                    $(this).find(".carg_desc").html(data[i]['desc']);
                    $(this).find(".carg_price").html(data[i]['price']);
                    if($.cookie(data[i]['no'])!=null)
                        $(this).find(".num").html($.cookie(data[i]['no']));
                    else
                        $(this).find(".num").html(0);
                    $(this).show();
                    i++;
                });
            }
        });
        }
    });

    // 给点击加号和减号绑定单击响应事件
    // 给减号绑定
    $(document).on("click", '.sub', function (){
        // console.log();
        if(parseInt($(this).parent().find(".num").html())!=0){
            $(this).parent().find(".num").html((parseInt($(this).parent().find(".num").html())-1));
            $("#cargo_sum_num").html(parseInt($("#cargo_sum_num").html())-1);
            $("#cargo_sum_money").html(parseFloat($("#cargo_sum_money").html())-parseFloat($(this).parent().parent().find(".carg_price").html()));
            $.cookie($(this).parent().parent().find(".carg_no").html(),$(this).parent().find(".num").html());
        }
    });

    // 给加号绑定
    $(document).on("click", '.plus', function (){
        // console.log($(this).parents().find(".num").html());
        $(this).parent().find(".num").html(parseInt($(this).parent().find(".num").html())+1);
        $("#cargo_sum_num").html(parseInt($("#cargo_sum_num").html())+1);
        $("#cargo_sum_money").html(parseFloat($("#cargo_sum_money").html())+parseFloat($(this).parent().parent().find(".carg_price").html()));
        $.cookie($(this).parent().parent().find(".carg_no").html(),$(this).parent().find(".num").html());
    });

    // 给下订单绑定单击响应事件
    $(document).on("click", '#order', function (){
        var aCookie = document.cookie.split(";");
        // console.log(document.cookie);
        var data=new Array(aCookie.length);
        for (var i = 0; i < aCookie.length; i++) {
            var aCrumb = aCookie[i].split("=");
            var temp={'no':aCrumb[0],'num':aCrumb[1]};
            data[i]=temp;
        }
        // for(var i=0;i<data.length;i++){
        //     console.log(data[i]['no'])
        // }
        // console.log(data)
        // console.log(data.length);
        // console.log(data)
        if(document.cookie=="")
            alert("您没有选中任何商品，请选购商品之后再下单。");
        else{
            var account=$("#account").html()
            $.ajax({
                url: "/store/customer/" + account,
                type:'post',
                data: {
                    'func': 'order',
                    'orderDetail':JSON.stringify(data)
                },
                success:function (data) {
                    if(data['num']=='0')
                        alert("您的个人信息不完整，请前往个人中心面板修改地址。");
                    else{
                        alert("下订单成功，若需结算请前往订单面板。");
                        location.reload();
                    }
                },
                error: function (error) {
                    console.log(error)
                }
            });
        }

    });

    // 给修改密码绑定单击响应事件
    $(document).on("click", '#modiPwd_btn', function (){
        // 获取账户号
        var account=$("#account").html()
        // 原密码
        var originPwd=$("#modiPwd input[name='originPwd']").val();
        // 新密码
        var newPwd=$("#modiPwd input[name='newPwd']").val();
        // 确认密码
        var affirmPwd=$("#modiPwd input[name='affirmPwd']").val();

        var func="modiPwd";
        var data={
            'func':func,
            'account':account,
            'oldPwd':originPwd,
            'newPwd':newPwd,
            'affirmPwd':affirmPwd
        };
        if(originPwd==""||newPwd==""||affirmPwd=="")
            alert("不允许有空信息被提交。");
        else {
            $.ajax({
                url:"/store/customer/" + account,
                type:'post',
                data:data,
                success: function (data) {
                    if(data['num']==1){
                        // 密码修改成功
                        alert("密码修改成功，请重新登录");
                        location.href="/store/login"
                    }
                    else if(data['num']==-1){
                        // 原密码输入错误
                        $("#error").html("原密码输入错误");
                    }
                    else {
                        // 新密码与确认密码不相符
                        $("#error").html("新密码与确认密码不相符");
                    }
                },
                error: function (error) {
                    console.log(error)
                }
            });
        }
    });

    // 给订单信息显示单选按钮绑定单击响应事件
    $(document).on("click", ':radio', function (){
        if($(this).val()=='notPay') {
            // 传递数据，获取未结算订单
            var account=$("#account").html()
            $.ajax({
                url:"/store/customer/" + account,
                type:'post',
                data:{
                    'func':'getNotPaidOrderForm'
                },
                success: function (data) {
                    $("#table1").html("");
                    var htmlAdd=""
                    // 加表首行
                    htmlAdd+='<tr> <th class="th1">序号</th> <th class="th2">时间</th> <th class="th3">账单描述</th> <th class="th4">总金额</th> <th class="th5">账单状态</th> </tr>'

                    // 将数据显示在每一行中
                    var dataLen=Object.keys(data).length;
                    for(var i=0;i<dataLen;i++){
                        htmlAdd+="<tr><td class='td1'>"+data[i]['no']+"</td><td class='td2'>"+data[i]['date']+"</td><td class='td3'>"+data[i]['desc']+"</td><td class='td4'>"+data[i]['total']+"元</td><td class='td5'>"+data[i]['status']+"</td></tr>"
                    }
                    $("#table1").html(htmlAdd);
                },
                error: function (error) {
                    console.log(error)
                }
            });
        }
        else if ($(this).val()=='paid'){
            var account=$("#account").html()
            // 传递数据，获取已结算订单
            $.ajax({
                url:"/store/customer/" + account,
                type:'post',
                data:{
                    'func':'getPaidOrderForm'
                },
                success: function (data) {
                    $("#table1").html("");
                    var htmlAdd=""
                    // 加表首行
                    htmlAdd+='<tr> <th class="th1">序号</th> <th class="th2">时间</th> <th class="th3">账单描述</th> <th class="th4">总金额</th> <th class="th5">账单状态</th> </tr>'

                    // 将数据显示在每一行中
                    var dataLen=Object.keys(data).length;
                    for(var i=0;i<dataLen;i++){
                        htmlAdd+="<tr><td class='td1'>"+data[i]['no']+"</td><td class='td2'>"+data[i]['date']+"</td><td class='td3'>"+data[i]['desc']+"</td><td class='td4'>"+data[i]['total']+"元</td><td class='td5'>"+data[i]['status']+"</td></tr>"
                    }
                    $("#table1").html(htmlAdd);
                },
                error: function (error) {
                    console.log(error)
                }
            });
        }
        else if ($(this).val()=='finish'){
            var account=$("#account").html()
            // 传递数据，获取已完成订单（包含申请退费订单）
            $.ajax({
                url:"/store/customer/" + account,
                type:'post',
                data:{
                    'func':'getFinishOrderForm'
                },
                success: function (data) {
                    $("#table1").html("");
                    var htmlAdd=""
                    // 加表首行
                    htmlAdd+='<tr> <th class="th1">序号</th> <th class="th2">时间</th> <th class="th3">账单描述</th> <th class="th4">总金额</th> <th class="th5">账单状态</th> </tr>'

                    // 将数据显示在每一行中
                    var dataLen=Object.keys(data).length;
                    for(var i=0;i<dataLen;i++){
                        htmlAdd+="<tr><td class='td1'>"+data[i]['no']+"</td><td class='td2'>"+data[i]['date']+"</td><td class='td3'>"+data[i]['desc']+"</td><td class='td4'>"+data[i]['total']+"元</td><td class='td5'>"+data[i]['status']+"</td></tr>"
                    }
                    $("#table1").html(htmlAdd);
                },
                error: function (error) {
                    console.log(error)
                }
            });
        }
        else {
            var account=$("#account").html()
            // 传递数据，获取已退费订单
            // console.log($(this).val())
            $.ajax({
                url:"/store/customer/" + account,
                type:'post',
                data:{
                    'func':'getRefundOrderForm',
                    'account':account
                },
                success: function (data) {
                    $("#table1").html("");
                    var htmlAdd=""
                    // 加表首行
                    htmlAdd+='<tr> <th class="th1">序号</th> <th class="th2">时间</th> <th class="th3">账单描述</th> <th class="th4">总金额</th> <th class="th5">账单状态</th> </tr>'

                    // 将数据显示在每一行中
                    var dataLen=Object.keys(data).length;
                    for(var i=0;i<dataLen;i++){
                        htmlAdd+="<tr><td class='td1'>"+data[i]['no']+"</td><td class='td2'>"+data[i]['date']+"</td><td class='td3'>"+data[i]['desc']+"</td><td class='td4'>"+data[i]['total']+"元</td><td class='td5'>"+data[i]['status']+"</td></tr>"
                    }
                    $("#table1").html(htmlAdd);
                },
                error: function (error) {
                    console.log(error)
                }
            });
        }
    });

    // 给td5绑定鼠标移入响应事件
    $(document).on("mouseover", '.td5', function (){
        if($("input[name=sel]:checked").val()=='notPay') {
            $(this).html("[去结算]");
            $(this).css("color",'red');
            $(this).css("text-decoration","underline");
        }
        else if($("input[name=sel]:checked").val()=='finish'){
            $(this).css("color",'red');
            $(this).css("text-decoration","underline");
            $(this).html("[申请退费]");
        }

    });

    // 给td5绑定鼠标移出响应事件
    $(document).on("mouseout", '.td5', function (){
        if($("input[name=sel]:checked").val()=='notPay'){
            $(this).html("未结算");
            $(this).css("color",'black');
            $(this).css("text-decoration","");
        }

        else if($("input[name=sel]:checked").val()=='finish'){
            $(this).html("已完成");
            $(this).css("color",'black');
            $(this).css("text-decoration","");
        }

    });

    // 给td5绑定单击响应事件
    $(document).on("click", '.td5', function (){
        if($("input[name=sel]:checked").val()=='notPay'){
            // 获取订单序号
            var orfo_no=$(this).parent().find(".td1").html()
            // 结算
            var account=$("#account").html()
            $.ajax({
                url:"/store/customer/" + account,
                type:'post',
                data:{
                    'func':'pay',
                    'orfo_no':orfo_no
                },
                success: function (data) {
                    if(data['num']==0)
                        alert("您的余额不够。");
                    else{
                        alert("订单结算成功。");
                        // location.reload();
                        $("#notPayForm").click();
                    }
                },
                error: function (error) {
                    console.log(error)
                }
            });
        }
    });
})
